<template>
  <div>
   <van-nav-bar fixed>
    <template #left>
      <img :src="imgSrc" alt="" class="logo">

    </template>
    <template #right>
      <van-icon name="search" size="0.48rem" color="#fff"  @click="$router.push('/search')"/>

    </template>

   </van-nav-bar>
     <van-tabs v-model="channelId" animated sticky   offset-top="1.226667rem">
  <van-tab v-for="item in channelsList" :title="item.name" :key="item.id"  :name="item.id">
<ArticleList :cid="channelId"></ArticleList>
  </van-tab>
</van-tabs>
<van-icon name="plus" size="0.37333334rem" class="moreChannels" @click="show=true" />
 <van-popup v-model="show" class="edit_wrap"  @closed="onPopupClosed">
      <!-- 弹出层的主体区域 -->
      <ChannelEdit @close="show=false"
       :userChannelsList='channelsList
       ' @addChannel="addChannelFn"
        @removeChannel="removeChannelFn"
        ref="ChannelEdit"
 @changeChannel="channgeChannelFn"
        ></ChannelEdit>
    </van-popup>
  </div>
</template>

<script>
import { userChannelAPI, updateChannelAPI } from '@/api'
import ttlogo from '@/assets/toutiao_logo.png'
import ArticleList from './ArticleList.vue'
import ChannelEdit from './ChannelEdit.vue'
export default {
  components: { ArticleList, ChannelEdit },
  data () {
    return {
      imgSrc: ttlogo,
      channelId: 0,
      channelsList: [],
      show: false
    }
  },
  methods: {
    async addChannelFn (val) {
      this.channelsList.push(val)
      this.updetaChannel()
    },
    removeChannelFn (val) {
      const index = this.channelsList.findIndex(item => item.id === val.id)
      this.channelsList.splice(index, 1)
      this.updetaChannel()
    },
    async updetaChannel () {
      const list = this.channelsList.filter(item => {
        return item.id !== 0
      })
      const resArr = list.map((item, index) => {
        const newObj = { ...item }
        newObj.seq = index + 1
        delete newObj.name
        return newObj
      })
      console.log(resArr)
      await updateChannelAPI({
        channels: resArr
      })
    },
    onPopupClosed () {
      this.$refs.ChannelEdit.isEdit = false
    },

    channgeChannelFn (val) {
      this.channelId = val.id // 传过来的频道ID, 影响tabs默认v-model的选择
    }

  },
  async created () {
    const res = await userChannelAPI()
    console.log(res)
    // const { channels } = res.data.data
    // this.channelsList = channels

    this.channelsList = res.data.data.channels
  }

}
</script>

<style lang="less" scoped>

.logo{
  width: 100px;
  height: 30px;
}
/* tab内容距离tab导航的距离 */
 /deep/ .van-tabs__content{
    padding-top: 44px;
 }
 // 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}
.edit_wrap{
  width: 100%;
  height: 100%;
}
</style>
